﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace DCT.CodeBox.Utility
{
    /// <summary>
    /// 文件IO类
    /// </summary>
    public static class FileUtility
    {
        /// <summary>
        /// 获取文件的真实Full地址
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string GetRealPath(string path)
        {
            path = path ?? "";
            if (path.StartsWith("~"))
            {
                path = HttpUtilityExt.HttpContext.Server.MapPath(path);
            }
            else
            {
                path = Path.GetFullPath(path);
            }
            return path;
        }

        /// <summary>
        /// 确保文件存在，如果文件不存在，则创建文件
        /// </summary>
        /// <param name="filepath"></param>
        /// <returns></returns>
        public static bool MakeSureFileExist(string filepath)
        {
            bool create = false;
            if (!File.Exists(filepath))
            {
                string folder = Path.GetDirectoryName(filepath);
                if (!Directory.Exists(folder)) {
                    Directory.CreateDirectory(folder);
                }
                using (File.Create(filepath))
                {
                }
                create = true;
            }
            return create;
        }

        /// <summary>
		/// 清除文件只读属性
		/// </summary>
		/// <param name="filePath">文件路径</param>
		public static void CleanFileReadOnly(string filePath)
		{
			//判断文件是否为只读
			if ((File.GetAttributes(filePath) & FileAttributes.ReadOnly) ==
				FileAttributes.ReadOnly)
			{
				//清除只读属性
				File.SetAttributes(filePath, FileAttributes.Normal);
			}
		}

		/// <summary>
		/// 复制文件到指定文件夹，并清除只读属性
		/// </summary>
		/// <param name="sourceFileName">源文件路径</param>
		/// <param name="destFileName">目标文件路径</param>
		/// <param name="isOverride">是否覆盖</param>
        public static void Copy(string sourceFileName, string destFileName, bool isOverride)
        {
            if (File.Exists(sourceFileName))
            {
                File.Copy(sourceFileName, destFileName, isOverride);
                CleanFileReadOnly(destFileName);	//清除只读属性
            }
        }
    }
}
